<?php
/**
 * @copyright Copyright (c) 2023 水月居工作室
 * @license https://opensource.org/licenses/Apache-2.0
 * @link https://www.ttxwgyxx.cn
 */

declare (strict_types = 1);

namespace app\home\controller;

use app\home\BaseController;
use think\facade\Db;
use think\facade\View;

class Lottery extends BaseController
{
    public function index()
    {
        add_user_log('view', '首页');
		$count = \think\facade\Db::name('UserLog')->where(array('type' => 'down'))->count();
        return View('',['count'=>$count]);
    }
    /**
     * 签到
     * */
    public function sign()
    {
        add_user_log('view', '签到');
        $avatarList=Db::name('LotteryAvatar')->select();
        view::assign('avatarlist',$avatarList);
        $count = \think\facade\Db::name('LotteryUser')->where(array('lottery_allow' => '1'))->count()+1;
        return View('',['count'=>$count]);
    }
        //上传签到信息
    public function checkSignIn()
    {
        $param = get_params();
        if(empty($param['avatar'])){
            return to_assign(1, '请选择头像！');
        }
        // dd($param);
        $data=[
            'real_name'=>$param['real'],//姓名
            'phone_number'=>$param['number'],//手机号
            'lottery_allow'=>1,//默认允许抽奖
            'lottery_done'=>0,//默认还没抽奖
        ];

        // dd($data);

        if($data['phone_number']!==null&&$data['real_name']!==null){
            //判断是否在名单里,不在则需要把身份设置为未知,且抽奖资格留空.
            $map['real_name']= $data['real_name'];
            // $map['phone_number'] =$data['phone_number'];
            //跟全部员工表的姓名做对比            
            $isInList=Db::name('LotteryStaff')->where($map)->find();
            //dd($isInList);
            if(empty($isInList)){
                //不在名单里
                $data['status']="未知";//身份
                $data['lottery_allow']=0;//不允许抽奖
                $data['sign_time'] = date('Y-m-d H:i:s',time());
                $avatar_id=$param['avatar']; 
                $data['avatar_url']=Db::name('LotteryAvatar')->where(['id'=>$avatar_id])->value('url');
                $profile = Db::name('LotteryUser')->save($data);
                if($profile){
                   $totalSignUserNumber=Db::name('LotteryUser')->count();
                   $msg ='签到成功,你是第'.$totalSignUserNumber.'位签到,由于您未在本次年会名单中,工作人员将会对您进行核查,谢谢!';
                   return redirect((string)url('/home/Lottery/showsuccess',['msg'=>$msg])); 
                }
                
            }
             //在抽奖名单里 redirect((string) url('hello',['name' => 'think']));
            $findUser=Db::name('LotteryUser')->where($map)->find();
            // dd($findUser); 
           if(!empty($findUser)){
              $msg='系统检测到您在'.$findUser['sign_time'].'已签到成功，签到id：'.$findUser['id'].'，请勿重复签到！';
              return redirect((string)url('/home/Lottery/showsuccess',['msg'=>$msg]));
            }else{
                $avatar_id=$param['avatar']; 
                $data['avatar_url']=Db::name('LotteryAvatar')->where(['id'=>$avatar_id])->value('url');
                $data['sign_time'] = date('Y-m-d H:i:s',time());
                if($isInList['status']=="嘉宾"){
                    $data['status']=$isInList['status'];
                    $data['lottery_allow']=1;//审核允许抽奖
                }elseif($isInList['status']=="员工"){
                    $data['status']=$isInList['status'];
                    $data['lottery_allow']=1;//审核允许抽奖
                }else{
                   $data['status']='未知';
                    $data['lottery_allow']=0;//审核不允许抽奖，需后台审核
                }

                //将抽奖人员状态设置与员工表 一致                
                $profile = Db::name('LotteryUser')->save($data);
                //dd($profile);
                if($profile){
                    //更新全部员工表中的签到状态
                    $up=Db::name('LotteryStaff')->where($map)->save(['signed'=>1]);//员工表中设置已签到标记
                    /*if($up)
                    {
                        echo "<script>alert('成功更新签到状态！')</script>";
                    }else{
                        echo "<script>alert('更新签到状态错误')</script>";
                    }*/

                    $totalSignUserNumber=Db::name('LotteryUser')->count();

                    //判断身份
                    if($data['status']==="嘉宾"){
                        $msg='签到成功,你是第'.$totalSignUserNumber.'位签到,因您是嘉宾，工作人员将会对您进行审核后，参与抽奖！谢谢！';
                    }elseif($data['status']=="员工"){//员工
                        $msg ='签到成功,你是第'.$totalSignUserNumber.'位签到,签到成功后可参加抽奖';

                    }else{
                        $msg ='签到成功,你是第'.$totalSignUserNumber.'位签到,由于您未在本次年会名单中,工作人员将会对您进行核查,谢谢!';                       
                        
                    }
                    View::assign('msg',$msg);
                    ;
                    return redirect((string)url('/home/Lottery/showsuccess',['msg'=>$msg])); 
                }
            }

        }else{
            echo "<script>alert('所有信息不能为空,且请填写正确的手机号码!')</script>";
            //$this->error('所有信息不能为空,且请填写正确的手机号码!');
        }

    }
    public function showsuccess(){
        $param = get_params();
        // dd($param);
        return View('sign-success',['msg'=>$param['msg']]);
    }
    /**
     * 前端抽奖平台等待开始按钮的post请求时,返回全部候选用户,用于滚动
     */
    public function lotteryPageAllSignUser(){
        //加上嘉宾和未知人员        
        $map['lottery_done']=0;//头像滚动只显示未中奖的
        $map['lottery_allow']=1;//允许抽奖的员工
        $res = Db::name('LotteryUser')->where($map)->select()->toArray();
        // dd($res);
        shuffle($res);
        echo json_encode($res);
    }
    /** 前端抽奖平台开始按钮的post请求,返回对应等级的抽奖用户结果.
    *   从数据库抽取用户后,在签到用户表做相应标记,不允许此轮用户进入下一轮抽奖.
    *   在中奖者表记录中奖人和生成兑奖号,并发送短信
    */
    public function lotteryNowLevel(){
        
        $nowLevel=Db::name('LotteryConfig')->where(['name'=>'now_level'])->value('content');
        
        echo $nowLevel;
    }
     /**
     * 进入抽奖页面
     */
    public function lottery_page(){

        $nowLevel =Db::name('LotteryConfig')->where(['name'=>'now_level'])->value('content');
        $level=Db::name('LotteryAwardGoods')->where(['award_level'=>$nowLevel])->find();
         // dump($level);die;
        $award_list = Db::name('LotteryAwardGoods')->order('id')->select();
        View::assign([
            'level'   => $level,
            'awardList' => $award_list
        ] );
        return View('start_lottery');
    }

    /**
     * 抽取获奖人员
     * */
	public function lotteryPageBegin(){
        header("Cache-Control: no-cache, must-revalidate");
       
        $nowLevel=Db::name('LotteryConfig')->where(['name'=>'now_level'])->value('content');
        $nowLevel =trim($nowLevel);

        if($nowLevel!==""){
             
             $levelNum=Db::name('LotteryAwardGoods')->where(['award_level'=>$nowLevel])->value('winner_number');//抽奖数量
             $limitNum=Db::name('LotteryAwardGoods')->where(['award_level'=>$nowLevel])->value('limit_number');//单次抽奖限定人数
             // dd($limitNum);
             $lotteryNum=$levelNum>$limitNum ? $limitNum : $levelNum;//抽奖总人数超过每次抽奖的限制人数则抽取单次设置人数 
             //剩余抽奖数大于0，则执行抽奖 
             if($levelNum>0) {
                $res = Db::query('SELECT * FROM wgy_lottery_user WHERE lottery_allow=1 and lottery_done=0   ORDER BY rand() LIMIT '.$lotteryNum);
                shuffle($res);
                echo json_encode($res);
                //抽取用户后,设置是否已经参加了抽奖....若数据库的符合条件的用户数小于抽奖预设数量???
                $doneNum =count($res);                
                for ($i = 0; $i< $doneNum; $i++) {
                    $condition['id'] = $res[$i]['id'];
                    $data['lottery_done'] = 1;

                    $getUserList=Db::name('LotteryUser')->where($condition)->save($data);////抽奖后标记好,不进入下一轮
                   // dump($getUserList); die;
                    if($getUserList){
                        //更新该用户在全部员工表中的等级状态                        
                        $map['real_name']=$res[$i]['real_name'];
                        $data4['level']=$nowLevel;
                        Db::name('LotteryStaff')->where($map)->save($data4);//在员工表中写入获奖等级
                        //逐个写入中奖表
                        $data1['real_name']=$res[$i]['real_name'];
                        $data1['phone_number']=$res[$i]['phone_number'];
                        $data1['level']=$nowLevel;
                        $data1['lottery_code']='2024'.$res[$i]['id'];
                        $data1['got_award']='否';//默认还没领奖
                        $data1['ctime']=date('Y-m-d H:i:s',time());
                        //$lotteryList=M('lottery_list');
                        $re =Db::name('LotteryList')->save($data1); 
                        $winner_number=Db::name('LotteryAwardGoods')->where('award_level',$nowLevel)->dec('winner_number')->update();//抽奖人数减一                       
                    }
                   
                }
             }            

        }else{
            $this->error('非法操作!','/Admin/Index/lotteryPage',2);
        }
    }
                                    
    public function logs()
    {
        add_user_log('view', '开发日志');
        return View('');
    }

	// public function down()
 //    {
 //        $version = CMS_VERSION;
 //        add_user_log('down', $version.'版本代码');
 //        header("Location: https://www.gougucms.com/storage/gougucms_v".$version."_full.zip");
 //        //确保重定向后，后续代码不会被执行
 //        exit;
 //    }
}
